package com.zeratul.common.event.base;


import cn.hutool.core.util.ObjectUtil;
import com.zeratul.common.core.utils.spring.SpringUtils;
import com.zeratul.common.event.base.interceptor.BasePublishInterceptor;
import com.zeratul.common.event.domain.ZtEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 发布者-服务层接口
 * author Ken
 * create_time 2022/9/17
 */
public interface BasePublishServer {

    Logger log = LoggerFactory.getLogger(BasePublishServer.class);

    /**
     * 发布事件对象
     * @param ztEvent
     * @param <T>
     */
    <T> void sendEvent(ZtEvent<T> ztEvent);

    /**
     * 发布层拦截器处理
     */
    default <T> ZtEvent<T> doInterceptor(ZtEvent<T> ztEvent) {
        //获取所有发布者拦截器
        Map<String, BasePublishInterceptor> publishInterceptors = SpringUtils.getBeansOfType(BasePublishInterceptor.class);
        //进行发布者拦截器的相关处理
        if(ObjectUtil.isEmpty(publishInterceptors)){
            return ztEvent;
        }

        for (BasePublishInterceptor publishInterceptor : publishInterceptors.values()) {
            try {
                //如果该拦截器不支持当前的消息对象，则跳过
                if (!publishInterceptor.isSupport(ztEvent)) {
                    continue;
                }

                //执行拦截器
                ztEvent = publishInterceptor.interceptor(ztEvent);
                //如果拦截器返回null, 则表示拦截器中断了消息的发送
                if (ObjectUtil.isNull(ztEvent)) {
                    return null;
                }
            } catch (Exception e) {
                log.warn("【事件总线】发布者拦截器异常！事件：{} 拦截器：{}", ztEvent, publishInterceptor.getClass().getName(), e);
            }
        }
        return ztEvent;
    }
}
